package emoji

import (
	"bufio"
	"bytes"
	_ "embed"
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"sync"
	"time"
)

//go:embed emoji-sequences.txt
var content []byte
var (
	emojiCache []rune
	cacheOnce  sync.Once
	cacheErr   error
)

// init 函数在包初始化时执行
func init() {
	rand.Seed(time.Now().UnixNano()) // 只在程序启动时设置随机种子
}

// GetEmojis 返回缓存的 emoji 列表，如果尚未缓存则解析文件
func GetEmojis() ([]rune, error) {
	cacheOnce.Do(func() {
		// 解析两个文件的 emoji 序列
		//当前文件的同级路径下的emoji-sequences.txt文件
		sequences1, err := parseEmojiRanges()
		if err != nil {
			cacheErr = err
			return
		}
		// 合并所有解析的 emoji
		emojiCache = append(sequences1)
	})

	return emojiCache, cacheErr
}

// parseEmojiRanges 解析文件中的 Unicode 代码点或范围
func parseEmojiRanges() ([]rune, error) {
	var emojis []rune
	scanner := bufio.NewScanner(bytes.NewReader(content))
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "#") || len(line) == 0 {
			continue
		}
		fields := strings.Fields(line)
		if len(fields) > 0 {
			codeRange := fields[0]
			if strings.Contains(codeRange, "..") {
				bounds := strings.Split(codeRange, "..")
				start, _ := strconv.ParseInt(bounds[0], 16, 32)
				end, _ := strconv.ParseInt(bounds[1], 16, 32)
				for i := start; i <= end; i++ {
					emojis = append(emojis, rune(i))
				}
			} else {
				codePoint, _ := strconv.ParseInt(codeRange, 16, 32)
				emojis = append(emojis, rune(codePoint))
			}
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return emojis, nil
}

// randomEmoji 随机选择一个 emoji
func randomEmoji(emojis []rune) rune {
	return emojis[rand.Intn(len(emojis))]
}

type EmojiService struct {
}

func (e *EmojiService) Make() rune {
	emojis, err := GetEmojis()
	if err != nil {
		fmt.Println("Error retrieving emojis:", err)
		return 0
	}

	emoji := randomEmoji(emojis)
	return emoji
}
